﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using AB.ServiceDirectory.BO;
using AB.ServiceDirectory.Commons;
using AB.ServiceDirectory.Entities;
using ServiceReference = AB.ServiceDirectory.Entities.ServiceReference;

namespace AB.ServiceDirectory.Design.Services
{
    public partial class ServiceDetails : Page
    {
        #region EVENTS

        /// <summary>
        /// </summary>
        /// Handles the Load event of the Page control.
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                LoadSubTypes();
                LoadServiceTypes();
                LoadInformationTab2Tab3();
                this.InitMode();
                this.InitPostBackValues();
            }
        }

        private void InitPostBackValues()
        {
            LabelCheckName.Text = string.Empty;
        }
        #region MyCH

        private static void SetSelectedItemsInCheckBoxList(string[] selectedIds, CheckBoxList checkBoxList)
        {
            foreach (ListItem item in checkBoxList.Items)
            {
                if (selectedIds.Contains(item.Value))
                {
                    item.Selected = true;
                }
            }
        }

        private ServiceReference ReferenceServiceInformation()
        {
            // Tab 2 - Reference
            var serviceReference = new ServiceReference();
            var disabilities = string.Join("-", CheckBoxDisability.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var barriers = string.Join("-", CheckBoxListBarriers.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var benefits = string.Join("-", CheckBoxListBenefits.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var circumstances = string.Join("-", CheckBoxListCircumstances.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var ethnicity = string.Join("-", CheckBoxEthnicity.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var accreditation = string.Join("-", CheckBoxListAccreditations.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var clientJourney = string.Join("-", CheckBoxListClientJourney.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var clientOutcome = string.Join("-", CheckBoxListClientOutcome.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var supportProcess = string.Join("-", CheckBoxListClientSupportProcess.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var participation = string.Join("-", CheckBoxListParticipation.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var referralSources = string.Join("-", CheckBoxListReferralSources.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var supportCentres = string.Join("-", CheckBoxListSupportCentres.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var targetClient = string.Join("-", CheckBoxTargetClient.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));

            serviceReference.DisabilityCriterion = disabilities;
            serviceReference.BarriersCriterion = barriers;
            serviceReference.BenefitsCriterion = benefits;
            serviceReference.PersonalCircumstancesCriterion = circumstances;
            serviceReference.EthnicityCriterion = ethnicity;
            serviceReference.Accreditations = accreditation;
            serviceReference.ClientOutcome = clientOutcome;
            serviceReference.ClientJourney = clientJourney;
            serviceReference.ParticipationCriterion = participation;
            serviceReference.ClientSupportProcess = supportProcess;
            serviceReference.SupportCentres = supportCentres;
            serviceReference.ReferralSources = referralSources;
            serviceReference.TargetClient = targetClient;
            int programId;
            serviceReference.ProgramId = int.TryParse(DropDownListProgram.SelectedValue, out programId)
                                             ? programId
                                             : (int?)null;

            return serviceReference;
        }

        private ServiceContract ContractInformation()
        {
            // Tab 3 - Contract 
            var contract = new ServiceContract();
            var contractOutCome = string.Join("-", CheckBoxListContractOutCome.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var contractObligation = string.Join("-", CheckBoxListContractObligation.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));

            contract.ContractOutcome = contractOutCome;
            contract.ContractObligation = contractObligation;
            contract.Participation = DropDownListPaticipation.SelectedValue;

            return contract;
        }

        private void LoadInformationTab2Tab3()
        {
            var serviceDetails = new ServiceDetail2BO();
            CheckBoxListBenefits.DataSource = serviceDetails.LoadCategorybyId(1);
            CheckBoxListBenefits.DataBind();

            CheckBoxListBarriers.DataSource = serviceDetails.LoadCategorybyId(2);
            CheckBoxListBarriers.DataBind();

            CheckBoxEthnicity.DataSource = serviceDetails.LoadCategorybyId(3);
            CheckBoxEthnicity.DataBind();

            CheckBoxDisability.DataSource = serviceDetails.LoadCategorybyId(4);
            CheckBoxDisability.DataBind();

            CheckBoxListCircumstances.DataSource = serviceDetails.LoadCategorybyId(5);
            CheckBoxListCircumstances.DataBind();

            CheckBoxListParticipation.DataSource = serviceDetails.LoadCategorybyId(6);
            CheckBoxListParticipation.DataBind();

            CheckBoxListClientSupportProcess.DataSource = serviceDetails.LoadCategorybyId(7);
            CheckBoxListClientSupportProcess.DataBind();

            CheckBoxListClientJourney.DataSource = serviceDetails.LoadCategorybyId(8);
            CheckBoxListClientJourney.DataBind();

            CheckBoxListSupportCentres.DataSource = serviceDetails.LoadCategorybyId(10);
            CheckBoxListSupportCentres.DataBind();

            CheckBoxListClientOutcome.DataSource = serviceDetails.LoadCategorybyId(11);
            CheckBoxListClientOutcome.DataBind();

            CheckBoxTargetClient.DataSource = serviceDetails.LoadCategorybyId(12);
            CheckBoxTargetClient.DataBind();

            CheckBoxListAccreditations.DataSource = serviceDetails.LoadCategorybyId(13);
            CheckBoxListAccreditations.DataBind();

            CheckBoxListReferralSources.DataSource = serviceDetails.LoadCategorybyId(14);
            CheckBoxListReferralSources.DataBind();

            CheckBoxListContractOutCome.DataSource = serviceDetails.LoadCategorybyId(15);
            CheckBoxListContractOutCome.DataBind();

            CheckBoxListContractObligation.DataSource = serviceDetails.LoadCategorybyId(16);
            CheckBoxListContractObligation.DataBind();

            DropDownListProgram.DataSource = serviceDetails.SelectPrograms();
            DropDownListProgram.DataBind();

            this.DropDownListPaticipation.Items.Add("Mandatory");
            this.DropDownListPaticipation.Items.Add("Voluntory");
            this.DropDownListPaticipation.Items.Add("Both");
        }

        private void LoadRefferenceData(Service service)
        {
            var serviceReference = service.ServiceReference;
            var serviceContract = service.ServiceContract;
            foreach (var item in ServiceDetail2BO.SelectInterventions(service.ServiceId))
            {
                var listItem = new ListItem
                                        {
                                            Selected = item.ServiceId != null,
                                            Text = item.InterventionName,
                                            Value = item.InterventionId.ToString()
                                        };
                CheckBoxListIntervention.Items.Add(listItem);
            }

            CheckBoxListOtherServices.DataSource = ServiceDetail2BO.GetOtherService(service.ServiceId);
            CheckBoxListOtherServices.DataBind();

            DropDownListProgram.DataSource = new ProgramBO().GetProgramList(null, null, -1, -1);
            DropDownListProgram.DataBind();
            DropDownListProgram.Items.Insert(0, new ListItem("None", string.Empty));
            if (serviceReference == null)
            {
                if (!string.IsNullOrEmpty(HiddenFieldServiceId.Value))
                {
                    var serviceId = int.Parse(HiddenFieldServiceId.Value);
                    serviceReference = ServiceBO.GetServiceReferenceById(serviceId);
                }
                if (serviceReference == null)
                {
                    return;
                }
            }
            string[] disabilities = (serviceReference.DisabilityCriterion ?? string.Empty).Split('-');
            string[] barriers = (serviceReference.BarriersCriterion ?? string.Empty).Split('-');
            string[] benefits = (serviceReference.BenefitsCriterion ?? string.Empty).Split('-');
            string[] circumstances = (serviceReference.PersonalCircumstancesCriterion ?? string.Empty).Split('-');
            string[] ethnicity = (serviceReference.EthnicityCriterion ?? string.Empty).Split('-');
            string[] accreditation = (serviceReference.Accreditations ?? string.Empty).Split('-');
            string[] clientOutcome = (serviceReference.ClientOutcome ?? string.Empty).Split('-');
            string[] targetClient = (serviceReference.TargetClient ?? string.Empty).Split('-');
            string[] clientJourney = (serviceReference.ClientJourney ?? string.Empty).Split('-');
            string[] referralSources = (serviceReference.ReferralSources?? string.Empty).Split('-');
            string[] supportCentres = (serviceReference.SupportCentres ?? string.Empty).Split('-');
            string[] supportProcess = (serviceReference.ClientSupportProcess ?? string.Empty).Split('-');
            string[] participationCriterion = (serviceReference.ParticipationCriterion ?? string.Empty).Split('-');
            string[] contractOutCome = (serviceContract.ContractOutcome ?? string.Empty).Split('-');
            string[] contractObligation = (serviceContract.ContractObligation ?? string.Empty).Split('-');

            SetSelectedItemsInCheckBoxList(accreditation, CheckBoxListAccreditations);
            SetSelectedItemsInCheckBoxList(ethnicity, CheckBoxEthnicity);
            SetSelectedItemsInCheckBoxList(disabilities, CheckBoxDisability);
            SetSelectedItemsInCheckBoxList(circumstances, CheckBoxListCircumstances);
            SetSelectedItemsInCheckBoxList(barriers, CheckBoxListBarriers);
            SetSelectedItemsInCheckBoxList(benefits, CheckBoxListBenefits);
            SetSelectedItemsInCheckBoxList(clientOutcome, CheckBoxListClientOutcome);
            SetSelectedItemsInCheckBoxList(targetClient, CheckBoxTargetClient);
            SetSelectedItemsInCheckBoxList(clientJourney, CheckBoxListClientJourney);
            SetSelectedItemsInCheckBoxList(referralSources, CheckBoxListReferralSources);
            SetSelectedItemsInCheckBoxList(supportCentres, CheckBoxListSupportCentres);
            SetSelectedItemsInCheckBoxList(participationCriterion, CheckBoxListParticipation);
            SetSelectedItemsInCheckBoxList(supportProcess, CheckBoxListClientSupportProcess);
            SetSelectedItemsInCheckBoxList(contractOutCome, CheckBoxListContractOutCome);
            SetSelectedItemsInCheckBoxList(contractObligation, CheckBoxListContractObligation);

            CheckBoxListOtherServices.DataSource = ServiceDetail2BO.GetOtherService(service.ServiceId);
            CheckBoxListOtherServices.DataBind();

            DropDownListProgram.SelectedValue = serviceReference.Program.ProgramId.ToString(CultureInfo.InvariantCulture);

            DropDownListPaticipation.SelectedValue = service.ServiceContract.Participation;

        }
        #endregion
        /// <summary>
        /// Loads the service types.
        /// </summary>
        private void LoadServiceTypes()
        {
            DropDownListServiceType.DataSource = DocumentUtilities.ServiceTypes;
            DropDownListServiceType.DataBind();
        }

        /// <summary>
        /// Loads the sub types.
        /// </summary>
        private void LoadSubTypes()
        {
            DropDownListSubType.DataSource = DocumentUtilities.ServiceSubTypes;
            DropDownListSubType.DataBind();
            DropDownListSubType.Items.Insert(0, new ListItem("None", string.Empty));
        }

        /// <summary>
        /// Inits the mode.
        /// </summary>
        private void InitMode()
        {
            int copyId;
            int serviceId = 0;
            // If copyId is existed, init copy mode for add a new service
            if (int.TryParse(Request.Params["copyId"], out copyId))
            {
                var service = ServiceBO.GetServiceById(copyId);
                if (service != null)
                {
                    service.ServiceId = 0;
                    service.ServiceName = string.Empty;
                    LoadDetails01(service);
                    ButtonSave.CommandName = "new";
                }
            }
            else if (int.TryParse(Request.Params["serviceId"], out serviceId))
            {
                var service = ServiceBO.GetServiceById(serviceId);
                if (service != null)
                {
                    LoadDetails01(service);
                    ButtonSave.CommandName = "edit";
                    HiddenFieldServiceId.Value = service.ServiceId.ToString(CultureInfo.CurrentCulture);
                    HiddenFieldServiceName.Value = service.ServiceName;
                    LoadRefferenceData(service);
                }
            }
            else
            {
                ButtonSave.CommandName = "new";
                LoadRefferenceData(new Service{ServiceId = 0});
            }
        }

        private void LoadDetails01(Service service)
        {
            if (service == null)
            {
                var serviceId = int.Parse(HiddenFieldServiceId.Value);
                service = ServiceBO.GetServiceById(serviceId);
                if (service == null)
                {
                    return;
                }
            }

            // Textbox fields
            TextBoxServiceName.Text = service.ServiceName;
            TextBoxShortDescription.Text = service.ShortDescription;
            TextBoxFullDescription.Text = service.FullDescription;
            TextBoxDeptCode.Text = service.DeptCode;
            TextBoxClientDescription.Text = service.ClientDescription;
            TextBoxDescriptionDelivery.Text = service.DescriptionDelivery;
            TextBoxContractCode.Text = service.ContractCode;
            TextBoxContractValue.Text = service.ContractValue;
            TextBoxStartExpected.Text = service.StartExpected != null
                                            ? service.StartExpected.Value.ToShortDateString()
                                            : string.Empty;
            TextBoxStartDate.Text = service.StartDate != null
                                        ? service.StartDate.Value.ToShortDateString()
                                        : string.Empty;
            TextBoxEndDate.Text = service.EndDate != null ? service.EndDate.Value.ToShortDateString() : string.Empty;
            TextBoxExtendableYears.Text = service.ExtendableYears != null ? service.ExtendableYears.Value.ToString(CultureInfo.CurrentCulture) : "0";
            TextBoxExtendableMonths.Text = service.ExtendableMonths != null
                                               ? service.ExtendableMonths.Value.ToString(CultureInfo.CurrentCulture)
                                               : "0";
            TextBoxLimitedMonths.Text = service.LimitedMonths != null
                                            ? service.LimitedMonths.Value.ToString(CultureInfo.CurrentCulture)
                                            : "0";
            TextBoxLimitedYears.Text = service.LimitedYears != null
                                            ? service.LimitedYears.Value.ToString(CultureInfo.CurrentCulture) : "0";
            TextBoxLeadContact.Text = service.Contact.FirstName + " " + service.Contact.Surname;
            HiddenFieldContactId.Value = service.Contact.ContactId.ToString(CultureInfo.CurrentCulture);

            // Dropdownlist
            DropDownListSubType.SelectedValue = service.SubType;
            DropDownListServiceType.SelectedValue = service.ServiceType;
            DropDownListServiceAttendance.SelectedValue = service.Attendance;
            DropDownListReferralProcess.SelectedValue = service.ReferrealProcess;

            // Checkbox
            CheckBoxActive.Checked = service.IsActive;
            CheckBoxStagedPayment.Checked = service.ContractStagedPayment != null && service.ContractStagedPayment.Value;
            CheckBoxServiceExtendable.Checked = service.ExtendableYears != null || service.ExtendableMonths != null;
            CheckBoxTimeLimited.Checked = service.LimitedYears != null || service.LimitedMonths != null;

            // Hidden field
            HiddenFieldServiceId.Value = service.ServiceId.ToString(CultureInfo.CurrentCulture);
            HiddenFieldServiceName.Value = service.ServiceName;
        }

        private Service GetServiceDetailsByForm()
        {
            var service = new Service();
            if (ButtonSave.CommandName.Equals("edit"))
            {
                service.ServiceId = int.Parse(HiddenFieldServiceId.Value);
            }
            service.ServiceName = TextBoxServiceName.Text.Trim();
            service.ShortDescription = TextBoxShortDescription.Text.Trim();
            service.FullDescription = TextBoxFullDescription.Text.Trim();
            service.SubType = DropDownListSubType.SelectedValue;
            service.DeptCode = TextBoxDeptCode.Text.Trim();
            service.ContactId = int.Parse(HiddenFieldContactId.Value);
            service.ClientDescription = TextBoxClientDescription.Text.Trim();
            service.Attendance = DropDownListServiceAttendance.SelectedValue;
            service.ServiceType = DropDownListServiceType.SelectedValue;
            service.DescriptionDelivery = TextBoxDescriptionDelivery.Text.Trim();
            service.ContractCode = TextBoxContractCode.Text.Trim();
            service.ContractValue = TextBoxContractValue.Text.Trim();
            service.ContractStagedPayment = CheckBoxStagedPayment.Checked;
            service.ReferrealProcess = DropDownListReferralProcess.SelectedValue;
            service.IsActive = CheckBoxActive.Checked;

            // Service extendable time
            if (CheckBoxServiceExtendable.Checked)
            {
                int extendableYears, extendableMonths;
                service.ExtendableYears = int.TryParse(TextBoxExtendableYears.Text, out extendableYears) ? extendableYears : (int?)null;
                service.ExtendableMonths = int.TryParse(TextBoxExtendableMonths.Text, out extendableMonths) ? extendableMonths : (int?)null;
            }

            // Service limited time
            if (CheckBoxTimeLimited.Checked)
            {
                int limitedYears, limitedMonths;
                service.LimitedYears = int.TryParse(TextBoxLimitedYears.Text, out limitedYears)
                                           ? limitedYears
                                           : (int?)null;
                service.LimitedMonths = int.TryParse(TextBoxLimitedMonths.Text, out limitedMonths)
                                           ? limitedMonths
                                           : (int?)null;
            }

            DateTime startExpected, startDate, endDate;
            service.StartExpected = DateTime.TryParse(TextBoxStartExpected.Text, out startExpected) ? startExpected : (DateTime?)null;
            service.StartDate = DateTime.TryParse(TextBoxStartDate.Text, out startDate) ? startDate : (DateTime?)null;
            service.EndDate = DateTime.TryParse(TextBoxEndDate.Text, out endDate) ? endDate : (DateTime?)null;

            return service;
        }

        private ICollection<Intervention> GetInterventionByForm(int serviceId)
        {
            var interventions = CheckBoxListIntervention.Items.Cast<ListItem>().Where(c => c.Selected).Select(
                        c =>
                        new Intervention { InterventionId = int.Parse(c.Value), ServiceId = serviceId }).ToList
                        ();
            return interventions;
        }

        /// <summary>
        /// Handles the Command event of the ButtonSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void ButtonSave_Command(object sender, CommandEventArgs e)
        {
            // Get information for service object
            var service = GetServiceDetailsByForm();
            service.ServiceReference = ReferenceServiceInformation();
            service.ServiceContract = ContractInformation();

            // Check name is exists
            if (!service.ServiceName.Equals(HiddenFieldServiceName.Value) &&
                ServiceBO.IsNameExists(service.ServiceName))
            {
                LabelCheckName.Text = "Service name must be unique";
                return;
            }

            // Saved result
            var savedResult = ButtonSave.CommandName.Equals("new")
                                  ? ServiceDetail2BO.AddService2(service)
                                  : ServiceDetail2BO.EditService2(service);
            if (savedResult)
            {
                var intervention = GetInterventionByForm(service.ServiceId);
                ServiceDetail2BO.EditIntervention(intervention);

                //DialogBox.Success("Save service successfully !");
            }
            else
            {
                DialogBox.Error("Cannot save service ");
            }
        }

        /// <summary>
        /// Handles the Command event of the ButtonInactive control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void ButtonInactive_Command(object sender, CommandEventArgs e)
        {
        }

        /// <summary>
        /// Handles the Command event of the ButtonLookup control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void ButtonLookup_Command(object sender, CommandEventArgs e)
        {
            ContactLookupPopup.Popup();
        }

        #endregion

        protected void CheckBoxServiceExtendable_CheckedChanged(object sender, EventArgs e)
        {

        }

        protected void CheckBoxTimeLimited_CheckedChanged(object sender, EventArgs e)
        {

        }

        protected void DropDownListSubType_SelectedIndexChanged(object sender, EventArgs e)
        {
            DetailsPanel06.Visible = false;
            DetailsPanel05.Visible = false;
            LinkDetails06.Visible = false;
            LinkDetails05.Visible = false;

            switch (DropDownListSubType.SelectedValue)
            {
                case "Contract":
                    DetailsPanel06.Visible = true;
                    LinkDetails06.Visible = true;
                    break;
                case "Funding":
                    DetailsPanel05.Visible = true;
                    LinkDetails05.Visible = true;
                    break;
            }
        }

    }
}